import { ref, nextTick, onMounted, onUnmounted } from 'vue'

export function useTableOfContents() {
  const headings = ref([])
  const activeHeading = ref('')
  const tocCollapsed = ref(false)
  const tocVisible = ref(true)
  
  // 滚动节流
  let scrollTimer = null
  
  // 更新活跃标题
  const updateActiveHeading = () => {
    if (headings.value.length === 0) return
    
    const headingElements = headings.value
      .map(h => document.getElementById(h.id))
      .filter(Boolean)
    
    if (headingElements.length === 0) return
    
    const scrollTop = window.scrollY + 120 // 导航栏高度偏移
    let current = ''
    
    for (let i = 0; i < headingElements.length; i++) {
      const element = headingElements[i]
      if (element.offsetTop <= scrollTop) {
        current = headings.value[i].id
      } else {
        break
      }
    }
    
    if (current && current !== activeHeading.value) {
      activeHeading.value = current
    }
  }
  
  // 节流滚动处理
  const handleScroll = () => {
    if (scrollTimer) {
      clearTimeout(scrollTimer)
    }
    scrollTimer = setTimeout(updateActiveHeading, 16) // ~60fps
  }
  
  // 滚动到指定标题
  const scrollToHeading = (id) => {
    const element = document.getElementById(id)
    if (element) {
      const offsetTop = element.offsetTop - 120 // 导航栏高度
      window.scrollTo({
        top: offsetTop,
        behavior: 'smooth'
      })
      activeHeading.value = id
    }
  }
  
  // 切换目录显示状态
  const toggleToc = () => {
    tocCollapsed.value = !tocCollapsed.value
  }
  
  // 自动隐藏/显示目录（基于屏幕宽度）
  const handleResize = () => {
    const width = window.innerWidth
    if (width < 1024) {
      tocVisible.value = false
      tocCollapsed.value = true
    } else {
      tocVisible.value = true
      tocCollapsed.value = false
    }
  }
  
  // 初始化目录
  const initToc = async (markdownContent) => {
    if (!markdownContent) return
    
    headings.value = extractHeadings(markdownContent)
    
    await nextTick()
    
    // 设置滚动监听
    window.addEventListener('scroll', handleScroll, { passive: true })
    window.addEventListener('resize', handleResize)
    
    // 初始化响应式状态
    handleResize()
    
    // 初始化活跃标题
    setTimeout(updateActiveHeading, 100)
  }
  
  // 提取标题的辅助函数
  const extractHeadings = (content) => {
    const lines = content.split('\n')
    const result = []
    
    lines.forEach((line, idx) => {
      const match = /^(#{2,6})\s+(.+)/.exec(line)
      if (match) {
        const level = match[1].length
        const text = match[2].trim()
        const id = `heading-${idx}-${text.replace(/\s+/g, '-').replace(/[^\w-]/g, '')}`
        result.push({ text, level, id, index: idx })
      }
    })
    
    return result
  }
  
  // 清理
  const cleanup = () => {
    window.removeEventListener('scroll', handleScroll)
    window.removeEventListener('resize', handleResize)
    if (scrollTimer) {
      clearTimeout(scrollTimer)
    }
  }
  
  onMounted(() => {
    handleResize()
  })
  
  onUnmounted(() => {
    cleanup()
  })
  
  return {
    headings,
    activeHeading,
    tocCollapsed,
    tocVisible,
    scrollToHeading,
    toggleToc,
    initToc,
    cleanup
  }
} 